package cn.elegent.txdemo.product.service.impl;

import cn.elegent.ac.ElegentAC;
import cn.elegent.tx.annotation.ElegentTx;
import cn.elegent.tx.context.ElegentACTXContext;
import cn.elegent.txdemo.common.dto.PayDto;
import cn.elegent.txdemo.product.entity.Product;
import cn.elegent.txdemo.product.feign.OrderFeign;
import cn.elegent.txdemo.product.feign.UserFeign;
import cn.elegent.txdemo.product.mapper.ProductMapper;
import cn.elegent.txdemo.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private UserFeign userFeign;


    @Override
    @ElegentTx(mainName = "pay",childName = "product")
    public void pay(PayDto payDto) {
        //购买商品扣减库存
        Product product = productMapper.selectById(payDto.getProductId());
        product.setNum( product.getNum()- payDto.getNum()   ); //扣库存
        productMapper.updateById( product );//更新商品表

        payDto.setPrice(product.getPrice() );//价格
        payDto.setProductName(product.getName());//商品名称
        ElegentACTXContext.setSnapshot("payDto",payDto); //保存快照
        orderFeign.saveOrder(payDto);
        userFeign.deduct(payDto);

    }


    @Override
    @Transactional
    public void payBack(PayDto payDto) {
        //购买商品扣减库存
        Product product = productMapper.selectById(payDto.getProductId());
        product.setNum( product.getNum()+ payDto.getNum()   ); //加库存
        productMapper.updateById( product );
    }
}
